package com.mrazola;

import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;

public class Sprite {
	
	private interface FrameSolver {
		public void nextFrame();
	}

	private Bitmap bitmap;
	private Rect animationFrame;
	private int frameWidth;
	private int currentFrame;
	private int totalFrames;
	private double fps;
	private double acumulatedTime;
	private FrameSolver frameSolver;
	
	public Sprite(Bitmap bitmap, int totalFrames, double fps) {
		this(bitmap, totalFrames, fps, false);
	}
	
	public Sprite(Bitmap bitmap, int totalFrames, double fps, boolean revert) {
		this.bitmap = bitmap;
		this.fps = fps;
		this.totalFrames = totalFrames;
		this.frameWidth = bitmap.getWidth() / totalFrames;
		animationFrame = new Rect(0, 0, frameWidth, bitmap.getHeight());	
		if (revert) {
			this.frameSolver = new ReversibleFrameSolver();
		} else {
			this.frameSolver = new CyclicFrameSolver();
		}
	}
	
	public void nextFrame(long elapsedTime) {
		acumulatedTime += elapsedTime;
		if (acumulatedTime / 1000 > 1 / fps) {
			acumulatedTime = 0 + elapsedTime % (1 / fps);
			acumulatedTime %= (1 / fps);
			frameSolver.nextFrame();
		}
	}
	
	//TODO It is not Sprite responsability to draw shadows...
	public void draw(Canvas canvas, Rect destination) {
		Paint shadow = new Paint();
		shadow.setShadowLayer(4, 8, 4, Color.BLACK);
		canvas.drawBitmap(bitmap.extractAlpha(), animationFrame, destination, shadow);
		canvas.drawBitmap(bitmap, animationFrame, destination, null);
	}
	
	private class CyclicFrameSolver implements FrameSolver {

		@Override
		public void nextFrame() {
			animationFrame.left = currentFrame * frameWidth;
			animationFrame.right = animationFrame.left + frameWidth;
			
			currentFrame++;
			currentFrame = currentFrame % totalFrames;
		}
		
	}
	
	private class ReversibleFrameSolver implements FrameSolver {
		
		private boolean reversed;
		
		@Override
		public void nextFrame() {
			
			if (currentFrame + 1 >= totalFrames) {
				reversed = true;
			}
			if (currentFrame <= 0) {
				reversed = false;
			}
			
			animationFrame.left = currentFrame * frameWidth;
			animationFrame.right = animationFrame.left + frameWidth;
			
			currentFrame = (reversed) ? currentFrame - 1 : currentFrame + 1;
			
		}
		
	}
	
}
